<?
class User
{
    var $groups = array(), $privilege = array(), $data = array('id'=> '0', 'email'=> '', 'user_name'=> '');
    static $current = FALSE, $permits = '', $permit_cats = '', $user_lock = 0;

    static $site_hit = 0;
    static $site_hit_month = 0;
    static $site_hit_day = 0;


    function User()
    {
        if (!isset($_SESSION['user_id'])) {
            $_SESSION['user_id'] = 0;
        }
        if ($_SESSION['user_id']) {
            $user = User::getUser((int)$_SESSION['user_id']);

            if ($user && (!USER_ACTIVE_ON || (USER_ACTIVE_ON && $user['is_active'] == 0))) {
                $this->groups = User::get_groups($user['gids']);

                if (!self::checkLock4Ever(TRUE)) {
                    if (!isset($this->groups[1]) && !isset($this->groups[2]) && $_SESSION['user_id'] != 4 && (trim($user['user_name']) == '' || $user['block_time'] > TIME_NOW || $user['block_time'] == -1)) {
                        self::$user_lock = 1;

                        if ($user['block_time'] == -1) { //Khoá vĩnh viễn
                            $user_lock = DB::select('user_lock', 'user_id=' . $user['id'] . ' AND type IN(1,3) ORDER BY id DESC', __LINE__ . __FILE__);

                            if ($user_lock) {
                                if ($user_lock['type'] == 3) { //Khoá cookie
                                    self::lock4Ever(TRUE, $user['id']);
                                }
                            }

                            self::LogOut();
                        } else {
                            //$_SESSION['user_lock'] = 1;
                            $this->data            = $user;
                            $_SESSION['user_name'] = $user['user_name'];
                        }
                    } else {
                        $this->data            = $user;
                        $_SESSION['user_name'] = $user['user_name'];
                    }
                }
            } else {
                self::LogOut();
            }
        }
    }

    static function checkLock4Ever($kick_out = FALSE)
    { //Hàm kiểm tra khoá người dùng vĩnh viễn từ cookie
        if (isset(User::$current->groups[1]) || isset(User::$current->groups[2]) || $_SESSION['user_id'] == 4) {
            if (isset($_SESSION['lock_4ever'])) $_SESSION['lock_4ever'] = 0;
            if (isset($_COOKIE['lock_4ever'])) AZLib::my_setcookie('lock_4ever', 0, TIME_NOW - 1);

            return FALSE;
        } else {
            if (isset($_COOKIE['lock_4ever']) || (isset($_SESSION['lock_4ever']) && $_SESSION['lock_4ever'])) {
                AZLib::my_setcookie('lock_4ever', 1);

                if ($kick_out) {
                    self::lock4Ever(TRUE);
                } else {
                    $_SESSION['lock_4ever'] = 1;
                }

                return TRUE;
            }

            return FALSE;
        }
    }

    static function lock4Ever($kick_out = FALSE, $user_id = FALSE)
    {
        AZLib::my_setcookie('lock_4ever', 1);
        User::LogOut();
        if ($kick_out && $user_id) {
            DB::delete(_SESS_TABLE, 'user_id=' . $user_id, __LINE__ . __FILE__);
        } else {
            $_SESSION['lock_4ever'] = 1;
        }
    }

    static function getUser($user_id, $update_cache = FALSE, $delcache = FALSE)
    {
        $user = array();
        if ($user_id) {
            if (MEMCACHE_ON) {
                if ($delcache) { //Xoá cache
                    if (MEMCACHE_ON) {
                        AZMemcache::do_remove("user:$user_id");
                    }

                    return TRUE;
                } else {
                    if (!$update_cache && MEMCACHE_ON) {
                        $user = AZMemcache::do_get("user:$user_id");
                    }

                    if (!$user) {
                        $sql  = "SELECT * FROM user WHERE id=" . (int)$user_id . " LIMIT 1";
                        $user = mysql_fetch_assoc(DB::query($sql));

                        $user['is_block'] = ($user['block_time'] > TIME_NOW || $user['block_time'] == -1) ? TRUE : FALSE;

                        if (MEMCACHE_ON && $user) {
                            AZMemcache::do_put("user:$user_id", $user);
                        }
                    }
                }
            } else { //cache file
                $subDir = 'user/' . floor($user_id / 1000);
                $user   = AZCache::cache('SELECT * FROM user WHERE id=' . (int)$user_id . ' LIMIT 0,1', __LINE__ . __FILE__, 2592000, $update_cache, '', $subDir, $delcache);
                if ($user && !$delcache) {
                    $user[0]['is_block'] = ($user[0]['block_time'] > TIME_NOW || $user[0]['block_time'] == -1) ? TRUE : FALSE;

                    return $user[0];
                }
            }
        }

        return $user;
    }

    static function getByUserName($user_name, $update_cache = FALSE, $delcache = FALSE)
    {
        $user = array();

        if ($user_name) {
            if (CACHE_ON) {
                $subDir    = 'user/user_by_user_name/';
                $user_temp = AZCache::cache("SELECT id FROM user WHERE user_name='$user_name' LIMIT 1", __LINE__ . __FILE__, 2592000, $update_cache, '', $subDir, $delcache);

                if ($user_temp) {
                    $subDir = 'user/' . floor($user_temp[0]['id'] / 1000);

                    return self::getUser($user_temp[0]['id'], $update_cache = FALSE, $delcache = FALSE);
                } else //Xóa cache nếu ko tồn tại
                {
                    AZCache::cache("SELECT id FROM user WHERE user_name='$user_name' LIMIT 1", __LINE__ . __FILE__, 2592000, 0, '', $subDir, 1);
                }
            } else {
                if ($user_name) {
                    $subDir = 'user/user_by_user_name/';
                    $user   = AZCache::cache("SELECT * FROM user WHERE user_name='$user_name' LIMIT 1", __LINE__ . __FILE__, 1, $update_cache, '', $subDir, $delcache);
                }
                if ($user && !$delcache) {
                    $user[0]['is_block'] = ($user[0]['block_time'] > TIME_NOW || $user[0]['block_time'] == -1) ? TRUE : FALSE;

                    return $user[0];
                }
            }
        }

        return $user;
    }

    static function updateUserCache($user_id)
    {
        if ($user_id)
            $user = User::getUser($user_id, TRUE);
        if ($user)
            return TRUE;

        return FALSE;
    }

    static function LogIn($user_or_id)
    {
        if (is_array($user_or_id) && isset($user_or_id['id']))
            $user_id = (int)$user_or_id['id'];
        else
            $user_id = $user_or_id;
        $_SESSION['user_id'] = $user_id;

        if ($user_id) {
            DB::query("UPDATE user SET last_ip='" . AZLib::ip() . "' WHERE id=" . $user_id, __LINE__ . __FILE__);
            $user = User::getUser($user_id);
            if ($user) {
                User::$current->data   = $user;
                $_SESSION['user_name'] = $user['user_name'];
            }
        }
    }

    static function LogOut()
    {
        if ((int)$_SESSION['user_id']) {
            DB::query("UPDATE user SET last_ip='" . AZLib::ip() . "' WHERE id=" . (int)$_SESSION['user_id'], __LINE__ . __FILE__);
        }

        $_SESSION['user_id']   = 0;
        $_SESSION['user_name'] = '';

        if (isset($_SESSION['user_lock'])) {
            $_SESSION['user_lock'] = NULL;
            unset($_SESSION['user_lock']);
        }

        #########################################
        if (isset($_SESSION['load_wish_list'])) {
            $_SESSION['load_wish_list'] = NULL;
            unset($_SESSION['load_wish_list']);
        }

        if (isset($_SESSION['wish_item'])) {
            $_SESSION['wish_item'] = NULL;
            unset($_SESSION['wish_item']);
        }
        #########################################

        if (isset($_SESSION['openid_url'])) {
            $_SESSION['openid_url'] = NULL;
            unset($_SESSION['openid_url']);
        }

        //Remove remember password cookies:
        if (isset($_COOKIE['az_id']) || isset($_COOKIE['password'])) {
            AZLib::my_setcookie('az_id', "", TIME_NOW - 3600);
            AZLib::my_setcookie('password', "", TIME_NOW - 3600);
        }
        AZLib::my_setcookie('user_wish_list_items', "", TIME_NOW - 3600);
    }

    static function is_block()
    {
        return self::$user_lock; //(isset($_SESSION['user_lock']) && $_SESSION['user_lock']);
    }

    static function is_login()
    {
        return (isset($_SESSION['user_id']) && $_SESSION['user_id'] != 0);
    }

    static function check_cookie_login($user_id, $password)
    {
        $user_data = DB::fetch('SELECT id, user_name, password, block_time, gids FROM user WHERE id=' . (int)$user_id, FALSE, FALSE, __LINE__ . __FILE__);

        if ($user_data && $user_data['password'] == $password) {
            if ($user_data['block_time'] > TIME_NOW) { //Nếu User bị khóa chưa hết hạn!
                self::LogOut();
            } else { //TuanNK sửa check quyền đăng nhập, nếu thuộc nhóm quản trị ==>> không cho đăng nhập tự động
                $in_group_admin = FALSE;
                if ($user_data['gids'] && $user_data['gids'] != '0') {
                    //$in_group_admin=(preg_match("/(".$user_data['gids'].")/is","2") || preg_match("/(".$user_data['gids'].")/is","1"));
                    $in_group_admin = (preg_match("/(" . $user_data['gids'] . ")/is", "3") || preg_match("/(" . $user_data['gids'] . ")/is", "2") || preg_match("/(" . $user_data['gids'] . ")/is", "1") || preg_match("/(" . $user_data['gids'] . ")/is", "9"));
                }

                if (!$in_group_admin) {
                    User::Login($user_data);
                    Url::redirect_url(Url::build_all());
                } else {
                    AZLib::my_setcookie('az_id', "", TIME_NOW - 3600);
                    AZLib::my_setcookie('password', "", TIME_NOW - 3600);
                }
            }
        } else {
            self::LogOut();
        }
    }

    static function encode_password($password)
    {
        return md5("tuannk_{$password}_AZnet");
    }

    static function is_root()
    { //power admin
        return 1;
       // return 1; //ngannv hack test

        return self::is_login() ? (isset(self::$current->groups['9']) || $_SESSION['user_id'] == 1) : FALSE;
    }

    static function is_admin()
    {
        return 1;
        return self::is_login() ? (isset(self::$current->groups['1']) || self::is_root() || $_SESSION['user_id'] == 4) : FALSE;
    }

    static function is_mod()
    {
        return self::is_login() ? (isset(self::$current->groups['2']) || self::is_admin()) : FALSE;
    }

    static function is_mod_cat()
    {
        return self::is_login() ? (isset(self::$current->groups['3']) || self::is_mod()) : FALSE;
    }

    static function is_az_team()
    {
        return self::is_login() ? (bool)self::$current->groups : FALSE;
    }

    static function check_admin($gids)
    {
        if ($gids && $gids != '0') {
            if (preg_match("/([\D])9([\D])/i", "|$gids|")) return 9; //Root
            elseif (preg_match("/([\D])1([\D])/i", "|$gids|")) return 1; //Admin
            elseif (preg_match("/([\D])2([\D])/i", "|$gids|")) return 2; //Mod
            elseif (preg_match("/([\D])3([\D])/i", "|$gids|")) return 3;
            //Mod for category
        }

        return 0;
    }

    static function check_higher_permis($gids_current, $gids)
    {
        $gids_current = self::check_admin($gids_current);
        $gids         = self::check_admin($gids);

        if ($gids == 9) { //is root
            if ($gids_current == 1 || $gids_current == 2 || $gids_current == 3) {
                return FALSE;
            }
        } elseif ($gids == 1) { //is admin
            if ($gids_current == 2 || $gids_current == 3) {
                return FALSE;
            }
        } elseif ($gids == 2) { //is mod
            if ($gids_current == 3) { //is mod cat
                return FALSE;
            }
        }

        return TRUE;
    }

    static function get_groups($gids)
    {
        $groups = array();
        if ($gids) {
            $gids_arr = explode('|', $gids);

            if ($gids_arr) {
                foreach ($gids_arr as $gid) {
                    if (isset(CGlobal::$group[$gid])) {
                        $groups[$gid] = CGlobal::$group[$gid];
                    }
                }
            }
        }

        return $groups;
    }

    static function id()
    {
        return isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
    }

    static function user_name()
    {
        if (isset($_SESSION['user_id'])) {
            if (isset($_SESSION['user_name']) && $_SESSION['user_name']) {
                return $_SESSION['user_name'];
            } elseif (isset(User::$current->data['user_name'])) {
                return User::$current->data['user_name'];
            }
        }

        return '';
    }

    static function level()
    {
        return self::is_az_team();
    }

    static function have_permit($pids)
    {
        if (User::is_login()) {
            if (is_array($pids)) {
                foreach ($pids as $pemiss) {
                    if (User::have_permit($pemiss))
                        return TRUE;
                }

                return FALSE;
            }

            if (User::is_admin()) {
                return TRUE;
            }

            if (User::$current->groups) { //Nếu đã phân nhóm
                self::get_permits();

                //return User::$permits!='' && User::$permits!='0' && preg_match("/(".User::$permits.")/is",$pids);
                return User::$permits != '' && User::$permits != '0' && preg_match("/([\D])" . $pids . "([\D])/is", '|' . User::$permits . '|');

                //return User::$permits!='' && User::$permits!='0' && preg_match("/".$pids."/is",User::$permits);
                //return User::$permits!='' && User::$permits!='0' && preg_match("/([$|\|]*)1([\|]*)/is","12|2");
                //return User::$permits!='' && User::$permits!='0' && preg_match("/([\D])12([\D])/i","12|2|3");#$filtro#i
            }
        }

        return FALSE;
    }

    static function have_cat_permit($catid)
    {
        if (User::is_login()) {
            if (User::have_permit(ADMIN_ITEM)) {
                return TRUE;
            }

            AZLib::getCats();

            if (!isset(CGlobal::$allCategories[$catid])) {
                return FALSE;
            }

            if (isset(User::$current->groups['3'])) { //Nếu đã phân nhóm
                self::get_permits();
                if (User::$permit_cats) {
                    if (CGlobal::$allCategories[$catid]['parent_id']) {
                        return preg_match("/(" . User::$permit_cats . ")/is", $catid) || preg_match("/(" . User::$permit_cats . ")/is", CGlobal::$allCategories[$catid]['parent_id']);
                    }

                    return preg_match("/(" . User::$permit_cats . ")/is", $catid);
                }
            }
        }

        return FALSE;
    }

    static function mod_have_cat_permit($catid)
    {
        if (User::is_login()) {
            if (User::have_permit(ADMIN_ITEM)) {
                return TRUE;
            }

            AZLib::getCats();

            if (!isset(CGlobal::$allCategories[$catid])) {
                return FALSE;
            }

            if (isset(User::$current->groups['4'])) { //Nếu đã phân nhóm
                self::get_permits();
                if (User::$permit_cats) {
                    if (CGlobal::$allCategories[$catid]['parent_id']) {
                        return preg_match("/(" . User::$permit_cats . ")/is", $catid) || preg_match("/(" . User::$permit_cats . ")/is", CGlobal::$allCategories[$catid]['parent_id']);
                    }

                    return preg_match("/(" . User::$permit_cats . ")/is", $catid);
                }
            }
        }

        return FALSE;
    }

    static function get_permits($del_cache = FALSE, $user_id = FALSE)
    {
        static $get_permits = 0;

        if ($del_cache && $user_id > 0 && $user_id != User::id()) {
            $user = User::getUser($user_id);
            if ($user) {
                $gids = str_replace('|', ',', $user['gids']);
            } else {
                return FALSE;
            }
        } elseif ($del_cache || !$get_permits) {
            $user_id = User::id();
            $gids    = str_replace('|', ',', self::$current->data['gids']);
        }

        if ($del_cache || !$get_permits) {
            $permits = AZCache::cache("SELECT type,ref_id,pids,cids FROM user_permit WHERE (ref_id IN(" . $gids . ") AND type=0) OR (ref_id=" . $user_id . " AND type=1)", __LINE__ . __FILE__, 36000, 0, '', '', $del_cache);
        }

        if (!$get_permits && !$del_cache) {
            if ($permits) {
                foreach ($permits as $permit) {
                    if ($permit['pids'])
                        User::$permits .= (User::$permits ? '|' : '') . $permit['pids'];
                    if ($permit['cids']) {
                        $permit['cids'] = str_replace(',', '|', $permit['cids']);
                        User::$permit_cats .= (User::$permit_cats ? '|' : '') . $permit['cids'];
                    }
                }
            }
            $get_permits = 1;
        }
    }

    static function check_get_user()
    {
        if (Url::get('user_id')) {
            if (User::is_login() && User::id() == Url::get('user_id')) {
                CGlobal::$user_profile = User::$current->data;
            } else
                CGlobal::$user_profile = User::getUser(Url::get('user_id'));
        }

        if (!CGlobal::$user_profile && Url::get('user_name')) {
            if (User::is_login() && User::user_name() == Url::get('user_name')) {
                CGlobal::$user_profile = User::$current->data;
            } else {
                CGlobal::$user_profile = User::getByUserName(Url::get('user_name'));
            }
        }
        if (!CGlobal::$user_profile && Url::get('id')) {
            if (User::is_login() && User::user_name() == Url::get('id')) {
                CGlobal::$user_profile = User::$current->data;
            } else {
                CGlobal::$user_profile = User::getByUserName(Url::get('id'));
            }
        }

        if (!CGlobal::$user_profile && User::is_login() && in_array(AZNet::$page['name'], array('personal', 'message',))) {
            CGlobal::$user_profile = User::$current->data;
        }

        if (!CGlobal::$user_profile) {
            Url::access_denied();
        }
    }


    static function getAdminNotice($update_cache = 0, $delcache = 0)
    {

        $arr_notices = array();
        $subDir      = 'AdminNotices/';

        $arr_notices = AZCache::cache("SELECT * FROM admin_notice WHERE active=1 ORDER BY id DESC LIMIT 10", __LINE__ . __FILE__, 0, $update_cache, '', $subDir, $delcache);

        if ($arr_notices && !$delcache) {
            return $arr_notices;
        }

        return $arr_notices;
    }

    static function getAdminNoticeUser($user_id, $update_cache = 0, $delcache = 0)
    {

        $arr_notices = array();
        $subDir      = 'Notices/' . floor($user_id / 1000) . '/' . $user_id;

        $arr_notices = AZCache::cache("SELECT * FROM admin_notice_user WHERE active=1 AND user_id = $user_id ORDER BY id DESC LIMIT 1", __LINE__ . __FILE__, 0, $update_cache, '', $subDir, $delcache);


        if ($arr_notices && !$delcache) {
            return $arr_notices;
        }

        return $arr_notices;
    }

    //Xử lý online
    static public function processOnline()
    {
        AZLib::get_config();

        $configs = @CGlobal::$configs['site_hit']['conf_val'];

        if ($configs != '') {
            $configs = unserialize(stripslashes($configs));
        } else {
            $configs = array(
                'site_hit'            => 1,
                'site_hit_month'      => 1,
                'site_hit_day'        => 1,
                'time'                => TIME_NOW
            );
        }

        $update       = FALSE;
        $update_month = FALSE;
        $update_day   = FALSE;

        $site_hit       = $configs['site_hit'];
        $site_hit_month = $configs['site_hit_month'];
        $site_hit_day   = $configs['site_hit_day'];

        $check_time = $configs['time'];

        //Site hit count in Month
        $time_start_month = mktime(0, 0, 0, date('m', TIME_NOW), 1, date('Y', TIME_NOW));

        if ($check_time <= $time_start_month) {
            $site_hit_month = 1;
            $update         = 1;
            $update_month   = 1;
        }

        //Site hit count in Day
        $time_start_day = mktime(0, 0, 0, date('m', TIME_NOW), date('d', TIME_NOW), date('Y', TIME_NOW));

        if ($check_time <= $time_start_day) {
            $site_hit_day = 1;
            $update       = 1;
            $update_day   = 1;
        }

        //Site hit
        if (!isset($_SESSION['site_hit'])) {
            $site_hit++;

            if (!$update_month) {
                $site_hit_month++;
            }

            if (!$update_day) {
                $site_hit_day++;
            }

            $_SESSION['site_hit'] = 1;

            $update = 1;
        }

        if ($update) {
            $configs = array(
                'site_hit'            => $site_hit,
                'site_hit_month'      => $site_hit_month,
                'site_hit_day'        => $site_hit_day,
                'time'                => TIME_NOW
            );

            if (isset(CGlobal::$configs['site_hit']))
                DB::update('configs', array("conf_val"=> addslashes(serialize($configs))), "conf_key='site_hit'");
            else
                DB::insert('configs', array("conf_key"=> 'site_hit', "conf_val"=> addslashes(serialize($configs))));

            AZLib::get_config(0, 1);
        }

        User::$site_hit       = $site_hit;
        User::$site_hit_month = $site_hit_month;
        User::$site_hit_day   = $site_hit_day;
    }
}

User::$current = new User();

User::processOnline();
?>